import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../widgets/platform/adaptive_card.dart';
import '../../../widgets/platform/adaptive_button.dart';
import '../../../widgets/platform/adaptive_text_field.dart';
import '../../../../core/platform/platform_detector.dart';

/// 角色管理页面
class RoleManagementPage extends ConsumerStatefulWidget {
  const RoleManagementPage({super.key});

  @override
  ConsumerState<RoleManagementPage> createState() => _RoleManagementPageState();
}

class _RoleManagementPageState extends ConsumerState<RoleManagementPage> {
  final _searchController = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    // 初始化时加载角色数据
    _loadRoles();
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  void _loadRoles() {
    // TODO: 实现加载角色数据的逻辑
  }

  void _searchRoles(String query) {
    // TODO: 实现搜索角色逻辑
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 搜索和操作栏
        _buildSearchBar(),
        const SizedBox(height: 16),

        // 角色列表
        Expanded(
          child: _buildRoleList(),
        ),
      ],
    );
  }

  Widget _buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      child: Row(
        children: [
          Expanded(
            child: AdaptiveTextField(
              controller: _searchController,
              labelText: '搜索角色',
              prefixIcon: Icons.search,
              hintText: '按角色名称或描述搜索',
              onChanged: _searchRoles,
            ),
          ),
          const SizedBox(width: 16),
          AdaptiveButton(
            onPressed: _showCreateRoleDialog,
            child: const SelectableText('创建角色'),
          ),
        ],
      ),
    );
  }

  Widget _buildRoleList() {
    // 模拟角色数据
    final roles = [
      {
        'code': 'ADMIN',
        'name': '系统管理员',
        'description': '拥有系统最高权限，可以管理用户、组织、角色等所有资源',
        'userCount': 1,
      },
      {
        'code': 'DEVELOPER',
        'name': '开发人员',
        'description': '负责系统开发和维护工作，可以创建和管理项目、待办任务等',
        'userCount': 3,
      },
      {
        'code': 'DEMANDER',
        'name': '需求方',
        'description': '负责需求管理和产品规划，可以创建项目和Excel计划',
        'userCount': 2,
      },
      {
        'code': 'TESTER',
        'name': '测试人员',
        'description': '负责系统测试工作，可以查看和执行测试任务',
        'userCount': 2,
      },
      {
        'code': 'DBA',
        'name': '数据库管理员',
        'description': '负责数据库管理和维护工作',
        'userCount': 1,
      },
    ];

    return LayoutBuilder(
      builder: (context, constraints) {
        // 桌面平台使用表格布局
        if (PlatformDetector.isDesktop() || PlatformDetector.isWeb()) {
          return _buildDesktopTable(roles);
        } else {
          // 移动平台使用卡片列表布局
          return _buildMobileList(roles);
        }
      },
    );
  }

  Widget _buildDesktopTable(List<Map<String, dynamic>> roles) {
    return SingleChildScrollView(
      child: DataTable(
        columns: const [
          DataColumn(label: SelectableText('角色代码')),
          DataColumn(label: SelectableText('角色名称')),
          DataColumn(label: SelectableText('描述')),
          DataColumn(label: SelectableText('用户数')),
          DataColumn(label: SelectableText('操作')),
        ],
        rows: roles.map((role) => _buildDataRow(role)).toList(),
      ),
    );
  }

  DataRow _buildDataRow(Map<String, dynamic> role) {
    return DataRow(
      cells: [
        DataCell(SelectableText(role['code'])),
        DataCell(SelectableText(role['name'])),
        DataCell(SelectableText(role['description'])),
        DataCell(SelectableText(role['userCount'].toString())),
        DataCell(
          Row(
            children: [
              IconButton(
                icon: const Icon(Icons.edit, size: 20),
                onPressed: () => _showEditRoleDialog(role),
              ),
              IconButton(
                icon: const Icon(Icons.delete, size: 20),
                onPressed: () => _showDeleteRoleDialog(role),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildMobileList(List<Map<String, dynamic>> roles) {
    return ListView.builder(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      itemCount: roles.length,
      itemBuilder: (context, index) {
        final role = roles[index];
        return _buildRoleCard(role);
      },
    );
  }

  Widget _buildRoleCard(Map<String, dynamic> role) {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(
                  Icons.security,
                  color: Theme.of(context).primaryColor,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SelectableText(
                      role['name'],
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                    ),
                    SelectableText(
                      role['code'],
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                            color: Colors.grey[600],
                          ),
                    ),
                  ],
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: Colors.blue.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: SelectableText(
                  '${role['userCount']} 用户',
                  style: const TextStyle(
                    color: Colors.blue,
                    fontSize: 12,
                  ),
                ),
              ),
              PopupMenuButton<String>(
                onSelected: (value) {
                  switch (value) {
                    case 'edit':
                      _showEditRoleDialog(role);
                      break;
                    case 'delete':
                      _showDeleteRoleDialog(role);
                      break;
                  }
                },
                itemBuilder: (context) => [
                  const PopupMenuItem(
                    value: 'edit',
                    child: Row(
                      children: [
                        Icon(Icons.edit, size: 20),
                        SizedBox(width: 8),
                        SelectableText('编辑'),
                      ],
                    ),
                  ),
                  const PopupMenuItem(
                    value: 'delete',
                    child: Row(
                      children: [
                        Icon(Icons.delete, size: 20),
                        SizedBox(width: 8),
                        SelectableText('删除'),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 12),
          SelectableText(
            role['description'],
            style: Theme.of(context).textTheme.bodyMedium,
          ),
        ],
      ),
    );
  }

  void _showCreateRoleDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('创建角色'),
        content: _buildRoleForm(),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: _handleCreateRole,
            child: const SelectableText('创建'),
          ),
        ],
      ),
    );
  }

  void _showEditRoleDialog(Map<String, dynamic> role) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('编辑角色'),
        content: _buildRoleForm(role: role),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: _handleUpdateRole,
            child: const SelectableText('保存'),
          ),
        ],
      ),
    );
  }

  void _showDeleteRoleDialog(Map<String, dynamic> role) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('确认删除'),
        content: SelectableText('确定要删除角色 "${role['name']}" 吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              _handleDeleteRole(role);
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const SelectableText('删除'),
          ),
        ],
      ),
    );
  }

  Widget _buildRoleForm({Map<String, dynamic>? role}) {
    return Form(
      key: _formKey,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          AdaptiveTextField(
            labelText: '角色代码',
            prefixIcon: Icons.code,
            initialValue: role?['code'] ?? '',
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入角色代码';
              }
              if (value.length < 2) {
                return '角色代码长度不能少于2位';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          AdaptiveTextField(
            labelText: '角色名称',
            prefixIcon: Icons.security,
            initialValue: role?['name'] ?? '',
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入角色名称';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          AdaptiveTextField(
            labelText: '角色描述',
            prefixIcon: Icons.description,
            maxLines: 3,
            initialValue: role?['description'] ?? '',
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入角色描述';
              }
              return null;
            },
          ),
        ],
      ),
    );
  }

  void _handleCreateRole() {
    if (_formKey.currentState!.validate()) {
      // TODO: 实现创建角色逻辑
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: SelectableText('角色创建成功')),
      );
    }
  }

  void _handleUpdateRole() {
    if (_formKey.currentState!.validate()) {
      // TODO: 实现更新角色逻辑
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: SelectableText('角色信息更新成功')),
      );
    }
  }

  void _handleDeleteRole(Map<String, dynamic> role) {
    // TODO: 实现删除角色逻辑
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: SelectableText('角色"${role['name']}"删除成功')),
    );
  }
}
